<?php
session_start();
require_once( 'student_db.php' );
require_once( 'stock_db.php' );

$user_id = $_SESSION['userid'];
$m_student = new M_Student();	
$m_stock = new M_Stock();

$cYear = $m_student->getCurrentYear();
$cTerm = $m_student->getCurrentTerm();

function MonthThai2($m){
	 $thaimonth=array("ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค."," มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค.");
	  
	 return $thaimonth[$m];

	}

 if (isset($_POST['m'])  &&  $_POST['m']!=""){
	if($_POST['m']== 'load_student_code'){
		$co = $_POST['code'];
		$result=$m_student->loadStudent($co,'',0,'', 0);
		$row = $result->FetchRow();
		echo json_encode($row);
		
   }else if ($_POST['m']== 'load_student'){
	  
      $cid = $_POST['classid'];
	  $r = $_POST['room'];
	  $n = $_POST['name'];
	  $co = $_POST['code'];
	  
      $result=$m_student->loadStudent($co,$n,$cid,$r, 0);
      $rows=$m_student->getRowCount();
      $i=1;
      $html="";
      if ($rows>0){
           $data = array();
            while($row = $result->FetchRow()){
               $data[] = array(0,$row['student_id'],$row['code'],$row['title_name'].' '.$row['thai_name'].' '.$row['thai_surname'].' ('.$row['thai_nickname'].')'
				, $row['class_name'].'/'.$row['room']) ;
            }
        }else{
			$data = array();
        }
    
        $arr = array('aaData'=>$data);
        
        echo json_encode($arr);
      
    } else if ($_POST['m'] == 'getProduct'){
			$t_product = $_POST['t'];

            $result = $m_stock->loadProduct($t_product);
            $rows = $m_stock->getRowCount();
            $i = 1;
            $html = "";
            if ($rows > 0) {
                $data = array();
                $id = array();

                while ($row = $result->FetchRow()) {
                    $id['id'] = $row['id'];
                    $id['label'] = $row['name'];
					$id['price'] = $row['price'];
                    $data[] = $id;
                }
            } else {
                $data = array();
            }
            echo json_encode($data);
	}else if ($_POST['m'] == 'pd_code'){
		$return  = array();
		$code=$_POST['code'];
		$amt = $_POST['amt'];
		$result = $m_stock->findProductByCode($code);
		
		if ($m_stock->getRowCount() > 0 ){
			$row=$result->FetchRow();
			if (($row['amt'] - $amt) < 0){
				$return=array('result'=>2 ,'txt'=>'สินค้าไม่พอจำหน่าย');
				 
			} else{	
				$return=array('result'=>1 ,'val'=>$row);	
			}
		
		}else {
			$return=array('result'=>0 ,'txt'=>'ไม่พบข้อมูล');
		}
		echo json_encode($return);
		
	}else if ($_POST['m'] == 'pd_id'){
	
		$return  = array();
		$pid=$_POST['pid'];
		$amt = $_POST['amt'];
		$result = $m_stock->findProductByID($pid);
		
		if ($m_stock->getRowCount() > 0 ){
			$row=$result->FetchRow();
			if (($row['amt'] - $amt) < 0){
				$return=array('result'=>2 ,'txt'=>'สินค้าไม่พอจำหน่าย');
				 
			} else{	
				$return=array('result'=>1 ,'val'=>$row);	
			}
		
		}else {
			$return=array('result'=>0 ,'txt'=>'ไม่พบข้อมูล');
		}
		echo json_encode($return);
	
	}else if ($_POST['m'] == 'buyPd'){
		$list=$_POST['list'];
		$code = str_replace("POSST","", $m_stock->getRunning("POSST"));
		$val['code']=$code;
		$val['year']=$cYear;
		$val['term']=$cTerm;
		$val['amt']=$_POST['amt'];
		$val['total']=$_POST['total'];
		$val['student_id']=$_POST['id'];
		$val['createdate'] =date( "Y/m/d H:i:s" );
		$val['createby'] = $user_id;
		$student_product_id = $m_stock->AddSudentProduct_header($val);
		
		foreach($list as $var){
			$var['student_product_id'] = $student_product_id;
			$m_stock->AddToStudentProduct($var);
			$m_stock->StockUpdate($var['product_id'],$var['amount'] ,$user_id );
		}
		
		echo $code;
		
	}else if ($_POST['m']=='load_stock_history_detail'){
		$id=$_POST['id'];
	 	
		$result=$m_stock->getStockHistoryDetail( $id );
		$rows=$m_stock->getRowCount();
		
		$i=1;
		$html="";
		if ($rows>0){
		   $data = array();
			while($row = $result->FetchRow()){
			   $data[] = array(0,$row['code'],$row['name'],$row['amount'],number_format( $row['price'] ,2,'.',',') ) ;
			}
		}else{
			$data = array();
		}

		$arr = array('aaData'=>$data);

		echo json_encode($arr);
		
		
	}else if ($_POST['m']=='load_st_histy'){
	  $id=$_POST['id'];
		 
	  $result=$m_stock->loadStudentStockHistory($id);
	  $rows=$m_stock->getRowCount();
	  $i=1;
	  $html="";
	  if ($rows>0){
		   $data = array();
			while($row = $result->FetchRow()){
			   $data[] = array(0,$row['id'],$row['code'],$row['create_date'],$row['year'] , $row['term'] ,$row['amt'] , $row['total'] 
				, $row['name']) ;
			}
		}else{
			$data = array();
		}

		$arr = array('aaData'=>$data);
		
		echo json_encode($arr);
		
	}else if ($_POST['m']=='load_pay_term'){
		$id=$_POST['id'];
		
		$result=$m_student->getPaymentTerm( $id, $cYear, $cTerm);
		$rows=$m_student->getRowCount();
		
		$i=1;
		$html="";
		if ($rows>0){
		   $data = array();
		   $course_name='';
			while($row = $result->FetchRow()){
				if ($row['fee_type'] == 6){
					if ($row['type']==1){
						if ($row['month']!=0){
							$course_name = $row['type_name'] .' [' . MonthThai2($row['month']-1).']';
						}else{
							$course_name = $row['type_name'] ;
						}
					}else{
						$course_name = $row['type_name'] ;
					}
				}else{
					$course_name = $row['type_name'];
				}
			   $data[] = array(0,$row['id'],$row['year'],$row['term']
						,$course_name
						,number_format( $row['amount'] ,2,'.',',') 
						, number_format( $row['pay_amount'] ,2,'.',',') 
						, number_format( $row['remain'] ,2,'.',',')
						,$row['fee_type']) ;
			}
		}else{
			$data = array();
		}

		$arr = array('aaData'=>$data);

		echo json_encode($arr);
	}else if ($_POST['m'] =='load_pay_history'){
		$id=$_POST['id'];
		
		$result=$m_student->getPaymentHistory( $id);
		$rows=$m_student->getRowCount();
		
		$i=1;
		$html="";
		if ($rows>0){
		   $data = array();
			while($row = $result->FetchRow()){
			   $data[] = array(0,$row['year'],$row['term'],$row['receipt_code'] ,$row['paydate']
						, $row['username'],number_format( $row['amount'] ,2,'.',',')  ) ;
			}
		}else{
			$data = array();
		}

		$arr = array('aaData'=>$data);

		echo json_encode($arr);
	}else if ($_POST['m']=='load_payment_detail'){ 
		$code=$_POST['code'];
		$result=$m_student->getPaymentHistoryDetail( $code );
		$rows=$m_student->getRowCount();
		
		$i=1;
		$html="";
		if ($rows>0){
		   $data = array();
		   $name='';
			while($row = $result->FetchRow()){
			$name=$row['type_name'];
			if($row['fee_type']==6){
				if ($row['type']==1){
					if ($row['month']!=0){
						$name=$row['type_name']. ' ['.MonthThai2($row['month']-1).']';
					}
				}
			}
			   $data[] = array(0,$name,number_format( $row['amount'] ,2,'.',',') ) ;
			}
		}else{
			$data = array();
		}

		$arr = array('aaData'=>$data);

		echo json_encode($arr);
		
	}else if ($_POST['m']=='del_term'){
		$id=$_POST['id'];
		$m_student->delPaymentTerm($id);
		
		echo "1";
	}else if ($_POST['m']=='pay_term'){
		$id=$_POST['id'];
		$ar['pay_amount'] =  $_POST['pay_amount'];
		$ar['isClose'] = $_POST['isClose'];
		$ar['pay_date'] = date( "Y/m/d H:i:s" );
		$ar['updateby'] = $user_id ;
		$ar['receipt_code'] = $m_student->getSlipRunning();
		$m_student->PaymentUpdate($id,$ar);
		
	}else if ($_POST['m']=='pay_term_date'){
		$id=$_POST['id'];
		$pay_date = "";
		if ($_POST['pay_date']!=''){
			list($d,$m,$y) = explode('/',$_POST['pay_date']);
		}
		$pay_date = $y.'/'.$m.'/'.$d;
		
		$ar['pay_amount'] =  $_POST['pay_amount'];
		$ar['pay_date'] = $pay_date;
		$ar['isClose'] = $_POST['isClose'];
		$ar['updateby'] = $user_id ;
		$ar['receipt_code'] = $m_student->getSlipRunning();
		$m_student->PaymentUpdate($id,$ar);
			
	}else if ($_POST['m'] =='pay_term_all'){
		$id=$_POST['id'];
		$code = $m_student->getSlipRunning();
		$m_student->PaymentUpdateAlll($id,$user_id,$code);
		echo $code;

	}else if ($_POST['m']=='update_course'){ 
		$values = $_POST['list'];
		$id = $_POST['id'];
		$rate=$m_student->getCourseRate();
		$student_id="";
		$total=0;
		$isFull=0;
		foreach($values as $val){
			$student_id=$val['sid'];
			$total += $val['cost'];
			if ($val['ctype']==1){ //normal
				// $rate['fix1']
				$type_1= $m_student->CourseNormal($val['id']);
				//print_r($type_1['cost']);
				//payfull this course
				if(($type_1['cost'] - $val['cost']) <= 0){
					//update tb_student_course is_pay=1
					$m_student->UpdatePayFullCourse($val['id'],$val['sid'],$cYear , $cTerm, $user_id );
					$isFull=1;
				//	print_r('payfull');
					//Add payment to teacher salary
					$m_student->checkCourseSalary($type_1['teacher'],2 , $rate['fix1'],$user_id);
				//	print_r('checkCourseSalary');
				} 
			}else if ($val['ctype']==2) { //special 
	 
				//$class_teacher = $m_student->getTeacherClass_By_StudentID($val['sid'],$cYear);
				//select teacher in course
				$type_3= $m_student->CourseNormal($val['id']);
				//print_r($type_3);
				//main teacher
				$main_rate =  $type_3['rate_1'];
				/*if ($class_teacher['teacher_1'] == $type_3['teacher']){
					$main_rate=$rate['fix2'];
				}else{
					$main_rate=$rate['fix3'];
				}*/
				//Reserve teacher
				$reserv_rate=$type_3['rate_2'];
				/*if ($class_teacher['teacher_2'] == $type_3['teacher2']){
					$reserv_rate=$rate['fix4'];
				}else{
					$reserv_rate=$rate['fix5'];
				}*/
				 
				//payfull this course
				if(($type_3['cost'] - $val['cost']) <= 0){
					$isFull=1;
					//update tb_student_course is_pay=1
					$m_student->UpdatePayFullCourse($val['id'],$val['sid'],$cYear , $cTerm, $user_id );
				//	print_r(1111);
					//Add payment to teacher salary
					$m_student->checkCourseSalary($type_3['teacher'], 3, $main_rate ,$user_id);
				//	print_r(222);
					//Add payment to reserv teacher
					$m_student->checkCourseSalary($type_3['teacher2'], 3, $reserv_rate ,$user_id);
				} 
				
			}else if ($val['ctype']==3){ // swim
				// rate['fix6']
				$type_2=$m_student->CourseSwimimg($val['id'],$val['sid'],$cYear , $cTerm);
				
				//payfull this course
				if(($type_2['cost'] - $val['cost']) <= 0){
					$isFull=1;
					//update tb_student_course is_pay=1
					$m_student->UpdatePayFullCourse($val['id'],$val['sid'],$cYear , $cTerm, $user_id );
					
					//Add payment to teacher salary swimimg
					$m_student->checkCourseSalary($type_2['teacher'], 4 , $rate['fix6'],$user_id);
				} 
			}
		}
		if ($isFull==1){
			$no = $m_student->getSlipRunning();
		}else
			$no='';
			
		$m_student->UpdatePaymentCourse($no,$id,$total,$user_id,$isFull);
		
	}else if ($_POST['m']=='load_course_by_student'){
		$id= $_POST['id'];
		$result=$m_student->getCourseListByID($id);
		$rows=$m_student->getRowCount();
		$i=1;
		if ($rows>0){
		   $data = array();
		   $name = '';
			while($row = $result->FetchRow()){
				if ($row['c_type']==1){
					if ($row['month']!=0){
						$name=$row['course_name']. ' ['.MonthThai2($row['month']-1).']';
					}else{
						$name=$row['course_name'];
					}
				}else{
					$name=$row['course_name'];
				}
			   $data[] = array(0,$row['id'],$row['student_id']
			   ,$row['course_type']
			   ,$name
			   ,number_format($row['cost'],2,'.',',').' บ. /'.$row['cost_type']
				, '<input type="text" class="text-right txtamt" maxlength="6" style="width:80px;" name="txtCost" value="'.$row['cost'].'"/>') ;
			}
		}else{
			$data = array();
		}

		$arr = array('aaData'=>$data);

		echo json_encode($arr);
		
	}else if ($_POST['m']=='addlist'){
		$fee_id= $_POST['fee_id'];
		$student_id = $_POST['sid'];
		$amt = $_POST['amt'];
		if ($m_student->CheckList($cYear,$cTerm ,$student_id,$fee_id)){
			$m_student->AddNewList($cYear,$cTerm ,$student_id,$fee_id, $amt);
			echo 0;
		}else{
			echo 1;
		}
		
	}

}else{
	if (isset($_GET['m']) && $_GET['m'] !="" ){
		if ($_GET['m'] == 'class'){
			echo json_encode( $m_student->getClassLevel());
		}else if ($_GET['m']=='room'){
			echo  json_encode( $m_student->load_all_room($_GET['i']));
		}else if ($_GET['m'] =='Term'){
			
			$html= $m_student->getCurrentYear() . "/". $m_student->getCurrentTerm() ;
			echo $html;
		
		}else if ($_GET['m']=='feetype'){
			echo  json_encode( $m_student->load_fee_type());
		}
	} 
}

?>